package com.hongyi.common.framework.config;


import com.hongyi.common.framework.utils.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PreDestroy;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author DingHao
 **/
@Slf4j
@Configuration
public class ThreadPoolConfig {

    /**
     * 全局线程池开关
     */
    @Value(value = "${thread-pool.enabled}")
    private Boolean enabled ;

    /**
     * 核心线程数 = cpu 核心数 + 1
     */
    private final int core = Runtime.getRuntime().availableProcessors() + 1;

    /**
     * 队列最大长度
     */
    @Value(value = "${thread-pool.queueCapacity}")
    private int queueCapacity;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    @Value(value = "${thread-pool.keepAliveSeconds}")
    private int keepAliveSeconds ;

    private ScheduledExecutorService scheduledExecutorService;


    /**
     * 全局线程池
     */
    @Bean(name = "threadPoolTaskExecutor")
    //当配置文件中thread-pool.enabled的值为true时，才会创建threadPoolTaskExecutor bean。否则，该bean不会被创建
    @ConditionalOnProperty(prefix = "thread-pool", name = "enabled", havingValue = "true")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        log.info("====创建全局线程池,核心线程数是：{}====",core);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(core * 2);//设置线程池的最大线程数为核心线程数的两倍
        executor.setCorePoolSize(core);//设置线程池的核心线程数为cpu 核心数 + 1
        executor.setQueueCapacity(queueCapacity);//设置线程池的任务队列容量为queueCapacity变量的值
        executor.setKeepAliveSeconds(keepAliveSeconds);//设置线程池中线程的空闲存活时间为keepAliveSeconds秒
        // 线程池对拒绝任务(无线程可用)的处理策略:设置线程池满时的拒绝策略为CallerRunsPolicy，这意味着如果线程池已满，提交的新任务将在调用者的线程中执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService() {
        //创建并返回一个新的ScheduledThreadPoolExecutor实例
        return new ScheduledThreadPoolExecutor(core,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build()) {//使用BasicThreadFactory来创建线程工厂，它将用于创建线程池中的线程
            @Override
            protected void afterExecute(Runnable r, Throwable t) {//每个任务执行完毕之后调用
                super.afterExecute(r, t);
                ThreadUtils.printException(r, t);
            }
        };
    }

    /**
     * 销毁事件
     */
    @PreDestroy
    public void destroy() {
        try {
            log.info("====关闭后台任务任务线程池====");
            ThreadUtils.shutdownAndAwaitTermination(scheduledExecutorService);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
